<?php

    class SocialController extends Zend_Controller_Action
    {

        public function init()
        {
            /* Initialize action controller here */
        }

        public function indexAction()
        {
            
        }

        public function activateaccountAction()
        {
            $email_model = new Application_Model_Email();
            $raeken_user_id = $this->_getParam("user_id");
            $raeken_user_id = getEncryptedString($raeken_user_id, "decode");
            $raeken_password = $this->_getParam("pswa");
            $raeken_password = getEncryptedString($raeken_password, "decode");


            $facebook = new Facebook(array(
                        'appId' => FACEBOOK_APP_ID,
                        'secret' => FACEBOOK_SECRET_ID,
                    ));

            // Get User ID
            $user = $facebook->getUser();

            if ($user)
            {
                try
                {
                    // Proceed knowing you have a logged in user who's authenticated.
                    $user_profile = $facebook->api('/me');

//                    prd($user_profile);
                    $model = new Application_Model_Common();
                    //record exists
                    $record = $model->getdata(RKN_USER, "facebook_id = '" . $user_profile["id"] . "'");

                    if (!empty($record))
                    {
                        $user_id = $record["rkn_uid"];

                        $this->_helper->FlashMessenger(
                                array('error' => '<strong>Oops!</strong> Facebook account already used!')
                        );

                        $this->_redirect("index/login");
                    }

                    $db = Zend_Registry::get('db');
                    $authAdapter = new Zend_Auth_Adapter_DbTable(
                                    $db, RKN_USER, 'rkn_uid', 'password', 'MD5(?) '
                    );


                    $authAdapter->setIdentity($raeken_user_id)
                            ->setCredential($raeken_password);

                    $zend_auth = Zend_Auth::getInstance();
                    $result = $zend_auth->authenticate($authAdapter);

                    if ($result->isValid())
                    {
                        $user = $authAdapter->getResultRowObject(null, 'password');
                        //check if the account is activated or not
//                        prd($user);
                        if ($user->status == '1')
                        {
                            $this->_helper->FlashMessenger(
                                    array('error' => '<strong>Oops!</strong> Your account is already activated!')
                            );

                            $this->_redirect("");
                        }
                        else
                        {
                            $data_array = array();
                            $data_array['status'] = '1';
                            $data_array['facebook_id'] = $user_profile["id"];
                            $data_array['facebook_username'] = $user_profile["username"];
                            $data_array['facebook_detail_array'] = json_encode($user_profile);
                            $data_array['fb_linked'] = '1';

                            $model->update($data_array, " rkn_uid = '$raeken_user_id' ");

                            $zend_auth->setStorage(new Zend_Auth_Storage_Session('User_Auth'));
                            $storage = $zend_auth->getStorage();
                            $storage->write($user);
                            
                            //send mail
                            $mailtext = $this->newRegisterationEmailTemplate($user->username,$user->first_name);
                            $registry = Zend_Registry::get('SITE_CONFIG');
                            $from_email = $registry['site_email'];
                            $site_name = $registry['site_name'];
                            $email_model->sendMail($user->email_address, $from_email, $site_name, "Thanks for joining us ", $mailtext);
                        }
                    }
                    else
                    {
                        $this->_helper->FlashMessenger(
                                array('error' => '<strong>Oops!</strong> Username or password is incorrect')
                        );
                        $this->_redirect("index/login");
                    }
                }
                catch (FacebookApiException $e)
                {
                    error_log($e);
                    $user = null;
                }
            }
            else
            {

                $this->_helper->FlashMessenger(
                        array('error' => '<strong>Oops!</strong> Some problem occurred while logging via facebook')
                );

                $this->redirect("index/login");
            }
            $raeken_user_id = $this->_getParam("user_id");
            $this->_redirect("index/index?user_id=" . $raeken_user_id . "&activate=true");
        }

        public function loginwithfacebookAction()
        {
            // Create our Application instance (replace this with your appId and secret).
            $facebook = new Facebook(array(
                        'appId' => FACEBOOK_APP_ID,
                        'secret' => FACEBOOK_SECRET_ID,
                    ));

            // Get User ID
            $user = $facebook->getUser();

            // We may or may not have this data based on whether the user is logged in.
            //
            // If we have a $user id here, it means we know the user is logged into
            // Facebook, but we don't know if the access token is valid. An access
            // token is invalid if the user logged out of Facebook.

            if ($user)
            {
                try
                {
                    // Proceed knowing you have a logged in user who's authenticated.
                    $user_profile = $facebook->api('/me');

//                    prd($user_profile);
                    $model = new Application_Model_Common();
                    //record exists
                    $check_username = $model->getdata(RKN_USER, "username = '" . $user_profile["username"] . "'");
                    $check_email = $model->getdata(RKN_USER, "email_address = '" . $user_profile["email"] . "'");
                    $record = $model->getdata(RKN_USER, "fb_id = '" . $user_profile["id"] . "'");
                    if (!empty($record))
                    {
                        $user_id = $record["rkn_uid"];
                    }

                    if (!empty($check_email))
                    {
                        //this email already exists
                        $update_data_array = array(
                            "user_facebook_id" => $user_profile["id"],
                            "facebook_username" => $user_profile["username"]
                        );
                        $model->updateRecordData($update_data_array, "user_email = '" . $user_profile["email"] . "'", RKN_USER);

                        if (empty($check_email["user_username"]))
                        {
                            $update_data_array = array(
                                "user_username" => $user_profile["username"]
                            );
                            $model->updateRecordData($update_data_array, "user_email = '" . $user_profile["email"] . "'", RKN_USER);
                        }

                        $_SESSION["messageSuccess"] = "Facebook account has been connected";

                        $user_id = $check_email["user_id"];
                    }
                    else if (!empty($check_username))
                    {
                        //this email already exists
                        $update_data_array = array(
                            "user_facebook_id" => $user_profile["id"],
                            "facebook_username" => $user_profile["username"]
                        );
                        $model->updateRecordData($update_data_array, "user_username = '" . $user_profile["username"] . "'", RKN_USER);

                        if (empty($check_email))
                        {
                            $update_data_array = array(
                                "user_email" => $user_profile["email"]
                            );
                            $model->updateRecordData($update_data_array, "user_email = '" . $user_profile["email"] . "'", RKN_USER);
                        }

                        $_SESSION["messageSuccess"] = "Facebook account has been connected";

                        $user_id = $check_email["user_id"];
                    }
                    else if (empty($check_email) && empty($check_username) && empty($record))
                    {
                        //insert record

                        $insert_data_array = array(
                            "user_first_name" => $user_profile["first_name"],
                            "user_last_name" => $user_profile["last_name"],
                            "user_username" => $user_profile["username"],
                            "user_email" => $user_profile["email"],
                            "facebook_username" => $user_profile["username"],
                            "user_active" => "1",
                            "user_facebook_id" => $user_profile["id"],
                            "user_ipaddress" => $_SERVER["REMOTE_ADDR"],
                        );
                        $model->insertRecordData($insert_data_array, RKN_USER);
                        $user_id = $model->getLastInsertId(RKN_USER);

                        $_SESSION["messageSuccess"] = "Please complete your account details";
                    }
                    $dbAdapter = Zend_Db_Table::getDefaultAdapter();
                    $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

                    $authAdapter->setTableName(RKN_USER)
                            ->setIdentityColumn('user_id')
                            ->setCredentialColumn('user_facebook_id');

                    $authAdapter->setIdentity($user_id)
                            ->setCredential($user_profile["id"]);

                    $zend_auth = Zend_Auth::getInstance();
                    $zend_auth->setStorage(new Zend_Auth_Storage_Session('User_Auth'));
                    $result = $zend_auth->authenticate($authAdapter);

                    if ($result->isValid())
                    {
                        $user = $authAdapter->getResultRowObject(null, 'user_password');
                        $zend_auth->getStorage()->write($user);
                    }
                    else
                    {
                        $_SESSION["messageError"] = "Error occured, please try again.";
                        $this->redirect("index");
                    }
                    $this->redirect("profile");
                }
                catch (FacebookApiException $e)
                {
                    error_log($e);
                    $user = null;
                }
            }
            else
            {
                $this->redirect("profile");
            }
        }

        public function loginwithtwitterAction()
        {
            // use the user's previously stored temporary credentials here
            $twitter = new TwitterOAuth(TWITTER_APP_ID, TWITTER_SECRET_ID, $_SESSION["oauth_token"], $_SESSION["oauth_token_secret"]);

            // uses the oauth_token (from the request) already.
            // you store these credentials in your database (see below).
            $credentials = $twitter->getAccessToken($_REQUEST["oauth_verifier"]);

            unset($_SESSION["oauth_token"]);
            unset($_SESSION["oauth_token_secret"]);

//            prd($credentials);
            if (isset($credentials["Invalid request token"]))
            {
                $_SESSION["messageError"] = "Invalid request token. Please try again.";
                $this->redirect("index");
            }

            $twitter_id = $credentials["user_id"];
            $twitter_username = $credentials["screen_name"];

            $model = new Application_Model_Common();
            //record exists
            $check_username = $model->getdata(RKN_USER, "user_username = '" . $twitter_username . "'");
            $record = $model->getdata(RKN_USER, "user_twitter_id = '" . $twitter_id . "'");

            if (!empty($record))
            {
                $user_id = $record["user_id"];
            }
            else if (!empty($check_username))
            {
                //this email already exists
                $update_data_array = array(
                    "user_twitter_id" => $twitter_id,
                    "twitter_username" => $twitter_username
                );
                $model->updateRecordData($update_data_array, "user_username= '" . $twitter_username . "'", RKN_USER);

                $_SESSION["messageSuccess"] = "Twitter account has been connected";

                $user_id = $check_username["user_id"];
            }
            else if (empty($check_username) && empty($record))
            {
                //insert record

                $insert_data_array = array(
                    "user_first_name" => $twitter_username,
                    "user_username" => $twitter_username,
                    "twitter_username" => $twitter_username,
                    "user_active" => "1",
                    "user_twitter_id" => $twitter_id,
                    "user_ipaddress" => $_SERVER["REMOTE_ADDR"],
                );
//                prd($insert_data_array);
                $model->insertRecordData($insert_data_array, RKN_USER);

                $user_id = $model->getLastInsertId(RKN_USER);

                $_SESSION["messageSuccess"] = "Please complete your account details";
            }

            $dbAdapter = Zend_Db_Table::getDefaultAdapter();
            $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

            $authAdapter->setTableName(RKN_USER)
                    ->setIdentityColumn('user_id')
                    ->setCredentialColumn('user_twitter_id');

            $authAdapter->setIdentity($user_id)
                    ->setCredential($twitter_id);

            $zend_auth = Zend_Auth::getInstance();
            $zend_auth->setStorage(new Zend_Auth_Storage_Session('User_Auth'));
            $result = $zend_auth->authenticate($authAdapter);

            if ($result->isValid())
            {
                $user = $authAdapter->getResultRowObject(null, 'user_password');
                $zend_auth->getStorage()->write($user);
                $_SESSION["messageSuccess"] = "You are logged in with twitter";
            }
            else
            {
                $_SESSION["messageError"] = "Error occured, please try again.";
                $this->redirect("index");
            }
            $this->redirect("profile");
        }

        public function loginwithlinkedinAction()
        {

            getAccessToken();

            function fetch($method, $resource, $body = '')
            {
                $params = array('oauth2_access_token' => $_SESSION['access_token'],
                    'format' => 'json',
                );

                // Need to use HTTPS
                $url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
                // Tell streams to make a (GET, POST, PUT, or DELETE) request
                $context = stream_context_create(
                        array('http' =>
                            array('method' => $method,
                            )
                        )
                );

                // Hocus Pocus
                $response = file_get_contents($url, false, $context);

                // Native PHP object, please
                return json_decode($response);
            }

            $user = fetch('GET', '/v1/people/~:(id,firstName,lastName,email-address)');
            if (isset($_GET['code']) && isset($_GET['state']))
            {
                $first_name = $user->firstName;
                $last_name = $user->lastName;
                $email = $user->emailAddress;
                $linkedin_id = $user->id;
//                prd($user);

                $model = new Application_Model_Common();
                //record exists
                $check_username = $model->getdata(RKN_USER, "user_username = '" . $email . "'");
                $check_email = $model->getdata(RKN_USER, "user_email = '" . $email . "'");
                $record = $model->getdata(RKN_USER, "user_linkedin_id = '" . $linkedin_id . "'");
                if (!empty($check_email))
                {
                    //this email already exists
                    $update_data_array = array(
                        "user_linkedin_id" => $linkedin_id,
                        "linkedin_username" => $email
                    );
                    $model->updateRecordData($update_data_array, "user_email = '" . $email . "'", RKN_USER);

                    if (empty($check_email["user_username"]))
                    {
                        $update_data_array = array(
                            "user_username" => $email
                        );
                        $model->updateRecordData($update_data_array, "user_email = '" . $email . "'", RKN_USER);
                    }

                    $_SESSION["messageSuccess"] = "LinkedIn account has been connected";

                    $user_id = $check_email["user_id"];
                }
                else if (!empty($check_username))
                {
                    //this email already exists
                    $update_data_array = array(
                        "user_linkedin_id" => $linkedin_id,
                        "linkedin_username" => $email
                    );
                    $model->updateRecordData($update_data_array, "user_username = '" . $email . "'", RKN_USER);

                    if (empty($check_email))
                    {
                        $update_data_array = array(
                            "user_email" => $email
                        );
                        $model->updateRecordData($update_data_array, "user_email = '" . $email . "'", RKN_USER);
                    }

                    $_SESSION["messageSuccess"] = "LinkedIn account has been connected";

                    $user_id = $check_email["user_id"];
                }
                else if (empty($check_email) && empty($check_username) && empty($record))
                {
                    //insert record

                    $insert_data_array = array(
                        "user_first_name" => $first_name,
                        "user_last_name" => $last_name,
                        "user_username" => $email,
                        "user_email" => $email,
                        "linkedin_username" => $email,
                        "user_active" => "1",
                        "user_linkedin_id" => $linkedin_id,
                        "user_ipaddress" => $_SERVER["REMOTE_ADDR"],
                    );
                    $model->insertRecordData($insert_data_array, RKN_USER);
                    $user_id = $model->getLastInsertId(RKN_USER);

                    $_SESSION["messageSuccess"] = "Please complete your account details";
                }
                $dbAdapter = Zend_Db_Table::getDefaultAdapter();
                $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

                $authAdapter->setTableName(RKN_USER)
                        ->setIdentityColumn('user_id')
                        ->setCredentialColumn('user_linkedin_id');

                $authAdapter->setIdentity($user_id)
                        ->setCredential($linkedin_id);

                $zend_auth = Zend_Auth::getInstance();
                $zend_auth->setStorage(new Zend_Auth_Storage_Session('User_Auth'));
                $result = $zend_auth->authenticate($authAdapter);

                if ($result->isValid())
                {
                    $user = $authAdapter->getResultRowObject(null, 'user_password');
                    $zend_auth->getStorage()->write($user);
                }
                else
                {
                    $_SESSION["messageError"] = "Error occured, please try again.";
                    $this->redirect("index");
                }
                $this->redirect("profile");
            }
            else
            {
                $this->redirect("profile");
            }
        }

        function newRegisterationEmailTemplate($username, $first_name)
        {
//            $social_fb_url = getShareWithFacebook('Our mission is to innovate the way people shop daily. We combine your favorite brands social content & products into a cool fun shoppable magazine. All you have to do is #demandyourspot now.');
            $social_fb_url = getShareWithFacebook(APPLICATION_URL);
            $social_twitter_url = getShareWithTwitter('I just demanded my spot @(' . $username . ') on raeken.com. Get your username before its too late #demandyourspot @raekenshop');
            $social_vimeo_url = "#";
            $social_insta_url = "#";

            $str = '
                        <body style="background-color: #EEEEEE;
                              font-size: 11px;
                              font-family: Arial;">
                            <table width="650" border="0" align="center" cellpadding="0" cellspacing="0">
                                <tr>
                                    <td style="margin-bottom:5px; text-align:center; padding-top: 30px;font-size:11px;display:block;">Email not displaying correctly ? <a style="color: #F38F00;" href="#">Click Here</a> to view it in your browser</td>
                                </tr>
                            </table>
                            <table width="650" border="0" align="center" cellpadding="0" cellspacing="0" style=" background-color: #fff;">
                                <tr>
                                    <td style="border-top-left-radius: 3px;
                                        border-top-right-radius: 3px;"><table width="100%" border="0" cellspacing="0" cellpadding="4">
                                            <tr>
                                                <td width="86%" style="padding-left: 10px;">
                                                    <a style="color: #F38F00;" href="'.APPLICATION_URL.'">
                                                        <img src="'. IMAGES_URL.'/email_templates/logo_email.png" alt="" width="78" height="19" style="padding: 3px;"/>
                                                    </a>
                                                </td>
                                                <td width="3%">
                                                    <a style="color: #F38F00;" href="https://www.facebook.com/raekenshop" target="_blank">
                                                        <img src="'. IMAGES_URL.'/email_templates/fb_email.png" alt="" width="24" height="23" style="padding: 3px;"/>
                                                    </a></td>
                                                <td width="3%">
                                                    <a style="color: #F38F00;" href=" https://twitter.com/raekenshop" target="_blank">
                                                        <img src="'. IMAGES_URL.'/email_templates/twt.png" alt="" width="23" height="23" style="padding: 3px;"/>
                                                    </a></td>
                                                <td width="3%">
                                                    <a style="color: #F38F00;" href="http://instagram.com/raekenshop" target="_blank">
                                                        <img src="'. IMAGES_URL.'/email_templates/inst.png" alt="" width="24" height="23" style="padding: 3px;"/>
                                                    </a></td>
                                                <td width="3%">
                                                    <a style="color: #F38F00;" href="http://pinterest.com/raekenshop">
                                                        <img src="'. IMAGES_URL.'/email_templates/pin.png" alt="" width="24" height="23" style="padding: 3px;"/>
                                                    </a></td>
                                            </tr>
                                        </table></td>
                                </tr>
                                <tr>
                                    <td><img src="'. IMAGES_URL.'/email_templates/bg.jpg" width="650" height="238" alt=""/></td>
                                </tr>
                                <tr>
                                    <td style="padding-top: 30px; font-size:12px;
                                        padding-right: 30px;
                                        padding-left: 30px;
                                        padding-bottom: 30px;"><p>Alright ' . $first_name . ', you claimed your spot in the revolution of online shopping!<br> 
                                            Your Raeken user name is: <strong style="color:#F7AD00">' . $username . '</strong><br>
                                            Our mission is to innovate the way people shop daily</p>
                                        <p>By integrating content from every major social media network into our magazine layout we give you an in-depth look at current trends, styling ideas and exactly what each brand is saying without ever you ever leaving the website.</p>
                                        <p>&ldquo;I want to raise the bar in online shopping & really shopping in general. I want to push the envelope & give people an unparalleled shopping experience&rdquo; -Kenny Dennis CEO of Raeken</p>
                                        <p>Call out to your social network and tell your friends to #DemandYourSpot at Raeken. 
                                            The official Raeken Store launches on June 1st. Until then, stay up to date on Raeken and the latest fashion trends by following our social media accounts and checking out our <span style="color:#F7AD00">blog.</span></p>

                                        <em>Whatever you do today make sure you are #RaisingTheBar.</em>
                                      </td>
                                </tr>
                            </table>
                            <table width="650" border="0" align="center" cellpadding="6" cellspacing="0">
                                <tr>
                                    <td style="text-align:center;font-size:11px;display:block;">Email not displaying correctly ? <a style="color: #F38F00;" href="#">Click Here</a> to view it in your browser</td>
                                </tr>
                            </table>
                        </body>
                        ';

            return $str;
        }

    }

    